<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb>
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品列表</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <!-- 消息提示区 -->
      <el-alert title="添加商品信息" type="info" center show-icon :closable='false'></el-alert>
      <!-- 步骤条区域 -->
      <el-steps :space="200" :active="activeIndex - 0" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- tab页面 -->
      <el-form :model="addForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm" label-position="top">
        <el-tabs :tab-position="'left'" v-model="activeIndex" :before-leave='beforeTabLeave' @tab-click='clickTabs'>
          <el-tab-pane label="基本信息" name='0' :disabled='isYes'>
            <!-- 商品名称 -->
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <!-- 商品价格 -->
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model.number="addForm.goods_price" type="Number"></el-input>
            </el-form-item>
            <!-- 商品重量 -->
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model.number="addForm.goods_weight" type="Number"></el-input>
            </el-form-item>
            <!-- 商品数量 -->
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model.number="addForm.goods_number" type="Number"></el-input>
            </el-form-item>
            <!-- 商品分类 -->
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader v-model="addForm.goods_cat" :options="cateList" :props="props" @change="handleChange"></el-cascader>
            </el-form-item>

          </el-tab-pane>
          <!-- 商品参数模块 -->
          <el-tab-pane label="商品参数" name='1' :disabled='isYes'>
            <el-form-item :label="item.attr_name" v-for="item in manyTableData" :key="item.attr_id">
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox v-for="(items, index) in item.attr_vals" :key="index" :label="items" border></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <!-- 商品属性模块 -->
          <el-tab-pane label="商品属性" name='2' :disabled='isYes'>
            <el-form-item :label="item.attr_name" v-for="item in onlyTableData" :key="item.attr_id">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name='3' :disabled='isYes'>
            <!-- 图片上传
            action是图片上传api地址 on-preview点击文件列表中已上传的文件时的钩子 on-remove文件列表移除文件时的钩子 file-list上传的文件列表-->
            <el-upload :action="uploadURL" :on-preview="handlePreview" :on-remove="handleRemove" :on-success="headersSuccess" list-type="picture" :headers='headersObj'>
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name='4' :disabled='isYes'>
            <!-- 富文本内容 -->
            <quill-editor v-model="addForm.goods_introduce" />
            <el-button type="primary" class="btn" @click="addGoods">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <!-- 图片预览 -->
    <el-dialog title="图片预览" :visible.sync="pictureVisible" width="40%">
      <img :src="pictureUrl" width="100%">
    </el-dialog>
  </div>
</template>

<script>
import _ from 'lodash'
export default {
  data () {
    return {
      activeIndex: 0,
      isYes: false,
      // 添加商品的数据
      addForm: {
        // 商品名称
        goods_name: '',
        // 商品价格
        goods_price: '',
        // 商品重量
        goods_weight: '',
        //  商品数量
        goods_number: '',
        // 商品所属的分类数组
        goods_cat: [],
        // 商品图片
        pics: [],
        // 商品介绍
        goods_introduce: '',
        // 商品的参数（数组），包含 `动态参数` 和 `静态属性`
        attrs: []
      },
      // 商品的验证规则
      rules: {
        goods_name: [
          // 商品名称验证规则
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        // 商品价格验证规则
        goods_price: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        // 商品重量验证规则
        goods_weight: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        // 商品数量验证规则
        goods_number: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        // 商品分类数据的绑定
        goods_cat: [
          { required: true, message: '请选择商品分类', trigger: 'blur' }
        ]
      },
      // 分类参数的数据
      cateList: [],
      // 商品分类的联级选择器的配置
      props: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      // 三级参数的静态数据分类
      manyTableData: [],
      // 动态参数
      onlyTableData: [],
      // 商品参数的复选框
      checkList: [],
      // 图片上传地址
      uploadURL: 'http://127.0.0.1:8888/api/private/v1/upload',
      // 处理图片请求的headers
      headersObj: {
        Authorization: sessionStorage.getItem('token')
      },
      // 图片预览的显示与隐藏
      pictureVisible: false,
      // 图片预览的显示地址
      pictureUrl: ''
    }
  },
  methods: {
    // 获取商品分类数据
    async getAddList () {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) return this.$message.error('获取失败')
      this.cateList = res.data
    },
    // 商品分类的触发事件
    handleChange () {
      // 判断商品分类是否选择的是3级分类不是则清空
      if (this.addForm.goods_cat.length !== 3) {
        this.addForm.goods_cat = []
      }
    },
    // tabs是否在上一个环节中选中
    beforeTabLeave (activeName, oldActiveName) {
      if (oldActiveName === '0' && this.addForm.goods_cat.length !== 3) {
        this.$message.error('请先把上一级选择完')
        return false
      }
    },
    // 选中tabs的时候执行的回调
    async clickTabs () {
      if (this.activeIndex === '1') {
        const { data: res } = await this.$http.get(
          `categories/${this.cetaId}/attributes`,
          {
            params: { sel: 'many' }
          }
        )
        if (res.meta.status !== 200) return this.$message.error('数据获取失败')
        this.manyTableData = res.data
        this.manyTableData.forEach((val) => {
          if (val.attr_vals.length !== 0) {
            val.attr_vals = val.attr_vals.split(',')
          }
        })
      }
      if (this.activeIndex === '2') {
        const { data: res } = await this.$http.get(
          `categories/${this.cetaId}/attributes`,
          {
            params: { sel: 'only' }
          }
        )
        if (res.meta.status !== 200) return this.$message.error('数据获取失败')
        this.onlyTableData = res.data
      }
    },
    // 处理图片预览
    handlePreview (flid) {
      this.pictureUrl = flid.response.data.url
      this.pictureVisible = true
    },
    // 处理删除图片的操作
    handleRemove (flid) {
      const i = this.addForm.pics.findIndex(
        (val) => val.pic === flid.response.data.tmp_path
      )
      this.addForm.pics.splice(i, 1)
    },
    // 图片上传成功后获取url
    headersSuccess (rease) {
      const success = {
        pic: rease.data.tmp_path
      }
      this.addForm.pics.push(success)
    },
    // 添加商品
    addGoods () {
      this.$refs.ruleForm.validate(async (val) => {
        if (!val) return this.$message.error('请填写完整')
        // 通过直接赋值获取
        // const addForm = this.addForm
        // addForm.goods_cat = addForm.goods_cat.join()

        this.manyTableData.forEach(val => {
          let attrVals = ''
          if (val.attr_vals) {
            attrVals = val.attr_vals.join()
          }
          const newCost = {
            attr_id: val.attr_id,
            attr_value: attrVals
          }
          this.addForm.pics.push(newCost)
        })
        this.onlyTableData.forEach(val => {
          const newCost = {
            attr_id: val.attr_id,
            attr_value: val.attr_vals
          }
          this.addForm.pics.push(newCost)
        })
        // 通过lodash _.defaults 深拷贝
        const form = _.defaults(this.addForm)
        form.attrs = this.addForm.attrs
        form.goods_cat = form.goods_cat.join()
        await this.$http.post('goods', form)
        this.$message.success('添加成功')
        this.$router.go(-1)
      })
    }
  },
  computed: {
    cetaId () {
      if (this.addForm.goods_cat.length === 3) {
        return this.addForm.goods_cat[2]
      }
      return null
    }
  },
  mounted () {
    this.getAddList()
  }
}
</script>

<style scoped lang='less'>
.el-checkbox {
  margin: 0 5px 0 0 !important;
}
.btn {
  margin-top: 17px;
}
</style>
